package com.yuven.baselib.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;


public class SPUtils {

    private static SharedPreferences sharedPreferences = null;



    public static void init() {
        sharedPreferences = getContext().getSharedPreferences(getContext().getPackageName(), Context.MODE_PRIVATE);
    }

    public static Context getContext(){
        return ToolsKit.getClient();
    }

    private static SharedPreferences getInstance() {
        if (sharedPreferences == null) {
            sharedPreferences = getContext().getSharedPreferences(getContext().getPackageName(), Context.MODE_PRIVATE);
        }
        return sharedPreferences;
    }

    public static String getString(String key, String defValue) {
        return getInstance().getString(key, defValue);
    }

    public static void putString(String key, String value) {
        SharedPreferences.Editor editor = getInstance().edit();
        editor.putString(key, value);
        editor.apply();
    }

    public static long getLong(String key, long defValue) {
        return getInstance().getLong(key, defValue);
    }

    public static void putLong(String key, long value) {
        SharedPreferences.Editor editor = getInstance().edit();
        editor.putLong(key, value);
        editor.apply();
    }

    public static int getInt(String key, int defValue) {
        return getInstance().getInt(key, defValue);
    }

    public static void putInt(String key, int value) {
        SharedPreferences.Editor editor = getInstance().edit();
        editor.putInt(key, value);
        editor.apply();
    }

    public static boolean getBoolean(String key, boolean defValue) {
        return getInstance().getBoolean(key, defValue);
    }

    public static void putBoolean(String key, boolean value) {
        SharedPreferences.Editor editor = getInstance().edit();
        editor.putBoolean(key, value);
        editor.apply();
    }

    public static void putObject(String key, Object obj) {
        putString(key, new Gson().toJson(obj));
    }

    public static <T> T getObject(String key, Class<T> model) {
        String s = getString(key, "");
        T t = null;
        try {
            t = new Gson().fromJson(s, model);
        } catch (Exception e) {
            // not handle exception
        }
        return t;
    }

    public static void clearPrefences() {
        SharedPreferences sharedPreferences = getInstance();
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();
    }

    public static void removeValue(String key) {
        SharedPreferences sharedPreferences = getInstance();
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(key);
        editor.apply();
    }
}
